package org.baojie.raft.serialization;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ConcurrentHashMap;

public abstract class AbstractSerialize implements Serialize {

    private static final Logger log = LoggerFactory.getLogger(AbstractSerialize.class);
    private static final Objenesis objs = new ObjenesisStd(true);
    private static final ConcurrentHashMap<Class<?>, Schema<?>> cache = new ConcurrentHashMap<>(128);

    static {
        System.getProperties().setProperty("protostuff.runtime.always_use_sun_reflection_factory", "true");
    }

    public AbstractSerialize() {

    }

    @Override
    public <T> byte[] serialize(T t) {
        if (null == t) {
            throw new NullPointerException("must not be null");
        }
        byte[] bytes = doSerialize(t);
        return bytes;
    }

    private <T> byte[] doSerialize(T t) {
        byte[] bytes = null;
        Class<T> cls = (Class<T>) t.getClass();
        Schema<T> schema = schema(cls);
        byte[] tmp = new byte[LinkedBuffer.DEFAULT_BUFFER_SIZE];
        LinkedBuffer buffer = LinkedBuffer.use(tmp);
        try {
            bytes = ProtostuffIOUtil.toByteArray(t, schema, buffer);
            if ((null == bytes) || (bytes.length == 0)) {
                bytes = new byte[0];
            }
        } finally {
            release(buffer, tmp);
        }
        return bytes;
    }

    private <T> Schema<T> schema(Class<T> cls) {
        if (null == cls) {
            throw new NullPointerException("must not be null");
        }
        Schema<T> schema = (Schema<T>) cache.get(cls);
        if (null == schema) {
            schema = RuntimeSchema.createFrom(cls);
        }
        if (null != schema) {
            cache.putIfAbsent(cls, schema);
        } else {
            throw new NullPointerException("create null class");
        }
        return schema;
    }

    private <T> void release(LinkedBuffer buffer, byte[] tmp) {
        if (null != buffer) {
            buffer.clear();
            buffer = null;
        }
        if (null != tmp) {
            tmp = null;
        }
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clz) {
        check(clz, bytes);
        T message = objs.newInstance(clz);
        Schema<T> schema = schema(clz);
        ProtostuffIOUtil.mergeFrom(bytes, message, schema);
        return message;
    }

    private <T> void check(Class<T> cls, byte[] bytes) {
        if (null == cls) {
            throw new NullPointerException();
        }
        if (null == bytes) {
            throw new NullPointerException();
        }
        if (bytes.length == 0) {
            throw new IllegalArgumentException();
        }
    }
}
